package com.yituo.mjworld.mvc.action.user;

import com.alibaba.fastjson.JSONObject;
import com.yituo.mjworld.core.annotation.NoToken;
import com.yituo.mjworld.core.annotation.Rule;
import com.yituo.mjworld.core.utils.OtherTool;
import com.yituo.mjworld.core.web.core.MyHttpRequest;
import com.yituo.mjworld.core.web.core.MyHttpResponse;
import com.yituo.mjworld.mvc.entity.UserData;
import com.yituo.mjworld.mvc.entity.other.MoblieCode;
import com.yituo.mjworld.mvc.service.impl.SmsServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.IOException;

/**
 * 增加短信接口
 */
@Component
public class SmsAction {

  @Autowired
  SmsServiceImpl smsService;


  /**
   * 发送验证码.
   *
   * @param req
   * @param res
   * @throws IOException
   */
  @NoToken
  @Rule(name = "mobile", name_zn = "手机号码", mobile = true)
  public void sendCode(MyHttpRequest req, MyHttpResponse res) throws IOException {
    String mobile = req.getParameter("mobile");
    try {
      int randCode = OtherTool.getCode();
      JSONObject sendResult = smsService.sendCode(mobile, randCode);
      System.out.println(sendResult);
      int sendCode = sendResult.getInteger("code");
      String authCode = sendResult.getString("obj");
      String msg = sendResult.getString("msg");
      if (sendCode == 200) {
        UserData.getMoblieCodeMap().put(mobile, new MoblieCode().setEndTime(System.currentTimeMillis()).setCode(authCode));
        res.success("发送成功!");
      } else {
        res.failed("发送失败!" + msg);
      }
    } catch (Exception e) {
      e.printStackTrace();
      res.failed("发送失败!");
      return;
    }
  }
}
